package anatex.kea.genex.genitor;

import java.util.*;

//TODO Implemetn Selection Bias 2.0!!!
public class Selector {

	protected TreeSet<Object[]> population;
	protected Double populationFitnessSum;
	protected HashMap<String, Double[]> roulette;
	
	public Selector(TreeSet<Object[]> pop) {
		population = pop;
	}
	
	protected void updateRouletteSlots() {
		Double slotOffset = 0.0;
		populationFitnessSum = 0.0;
		roulette = new HashMap<String, Double[]>();
		
		//update population fitness sum
		for (Object[] item : population) {
			populationFitnessSum += (Double)item[1];
		}
		
		for (Object[] item : population) {
			roulette.put((String)item[0], new Double[] {new Double(slotOffset), new Double(slotOffset + ((Double)item[1] / populationFitnessSum))});
			
			slotOffset += ((Double)item[1] / populationFitnessSum);
		}
	}
	
	public String[] select() {
		String[] parents = {"",  ""};
		
		updateRouletteSlots();
		
		Random rand = new Random();
		Double r;
		for (int i = 0; i < 2; i ++) {
			r = rand.nextDouble();
			
			Double[] range = new Double[] {0.0, 0.0};
			for (String chromosome : roulette.keySet()) {
				range = (Double[])roulette.get(chromosome);
				
				if (range[0] <= r && r <= range[1]) {
					if (i > 0 && chromosome == parents[i - 1]) {
						i --;
						
						break;
					}
					
					parents[i] = chromosome;
					
					break;
				}
			}
			
			//if no parent was found for the randomly selected double
			if ("" == parents[i]) {
				i --;
			}
		}
		
		return parents;
	}
	
}
